﻿using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Infrastructure.Utilities;
using System;

namespace JuCheap.Core.Data.Entity
{
    /// <summary>
    /// 数据实体基类
    /// </summary>
    public interface IBaseEntity
    {
        /// <summary>
        /// 主键
        /// </summary>
        string Id { get; set; }

        /// <summary>
        /// 公司Id
        /// </summary>
        string CompanyId { get; set; }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        bool IsDeleted { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        DateTime CreateTime { get; set; }

        /// <summary>
        /// 创建人Id
        /// </summary>
        string CreateUserId { get; set; }

        /// <summary>
        /// 修改时间
        /// </summary>
        DateTime? ModifyTime { get; set; }

        /// <summary>
        /// 修改人Id
        /// </summary>
        string ModifyUserId { get; set; }
    }

    /// <summary>
    /// 实体扩展
    /// </summary>
    public static class IBaseEntityExtention
    {
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="user">当前用户</param>
        public static void Create(this IBaseEntity entity, CurrentUserDto user = null)
        {
            if (entity.Id.IsBlank())
            {
                entity.Id = SnowFlake.NewId();
            }
            entity.CreateTime = DateTime.Now;
            if (user != null)
            {
                if (entity.CompanyId.IsBlank())
                {
                    entity.CompanyId = user.CompanyId;
                }
                if (entity.CreateUserId.IsBlank())
                {
                    entity.CreateUserId = user.UserId;
                }
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="user">当前用户</param>
        public static void Modify(this IBaseEntity entity, CurrentUserDto user = null)
        {
            entity.ModifyTime = DateTime.Now;
            if(user != null)
            {
                entity.ModifyUserId = user.UserId;
            }
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="user">当前用户</param>
        public static void Delete(this IBaseEntity entity, CurrentUserDto user = null)
        {
            entity.IsDeleted = true;
            entity.ModifyTime = DateTime.Now;
            if (user != null)
            {
                entity.ModifyUserId = user.UserId;
            }
        }
    }
}
